package com.brycen.bio.file;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端：文件传输
 * 使用DataOutputStream字节流分段输出文件后缀和文件内容
 */
public class client {
    public static void main(String[] args)  {
        Socket socket = null;
        FileInputStream fis=null;
        DataOutputStream dos=null;
        try {
            socket = new Socket("127.0.0.1",9999);
            OutputStream outputStream = socket.getOutputStream();

            String filePath = "/Users/liuyu/Desktop/iodemo/print.txt";
            fis = new FileInputStream(filePath);

            //使用DataOutputStream进行分段发送
            dos = new DataOutputStream(outputStream);
            //发送文件后缀
            String[] split = filePath.split("\\.");
            String suffix = "."+split[1];
            dos.writeUTF(suffix);

            byte[] buffer = new byte[1024];
            int len;
            while ((len=fis.read(buffer))>0){
                //发送文件内容
                dos.write(buffer,0,len);
            }
            //告诉服务端，数据发送完成
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭资源
                if (socket!=null){
                    socket.close();
                }
                if (fis!=null){
                    fis.close();
                }
                if (dos!=null){
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
